package com.lzyyj.gmis.base.webui;

import com.lzyyj.gmis.base.model.ThemeSkin;
import com.lzyyj.gmis.base.model.ThemeStyle;
import com.lzyyj.gmis.base.model.ThemeType;
import com.lzyyj.gmis.base.service.IThemeService;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import java.io.IOException;
import java.util.Map;

/**
 * 主题类型及风格处理过滤器
 * 为jsp页面提供统一的主题类型及风格设置，保存咋request中，key可配置，
 * 默认key分别为themeType和themeStyle，jsp中可以用 ${themeType} 和 ${themeStyle}进行引用
 * @author lzyyj
 *
 */
public class ThemeFilter implements Filter {
	
	private static Log log = LogFactory.getLog(ThemeFilter.class);
	
	private IThemeService themeService;
		
	private String themeRootKey = "ThemeRoot";

	private String themeTypeKey = ThemeSkin.THEME_TYPE_KEY;

	private String themeStyleKey = ThemeSkin.THEME_STYLE_KEY;

	private String themeMainCssKey = ThemeSkin.THEME_MAIN_CSS_KEY;
	
	private String defaultThemeRoot = "Skin";

	private String defaultThemeType = "SiteWeaver";

	private String defaultThemeStyle = "Default" ;
	
	private ThemeSkin themeSkin;
	
	/**
	 * 初始化过滤器相关设施
	 */
	@Override
    public void init(FilterConfig filterConfig) throws ServletException {
		
		log.debug("初始化过滤器！");

		themeRootKey = getInitParameter(filterConfig, "themeRootKey", themeRootKey);
		
		themeTypeKey = getInitParameter(filterConfig, "themeTypeKey", themeTypeKey);
		
		themeStyleKey = getInitParameter(filterConfig, "themeStyleKey", themeStyleKey);
		
		themeMainCssKey = getInitParameter(filterConfig, "themeMainCssKey", themeMainCssKey);
		
		defaultThemeRoot =  getInitParameter(filterConfig, "defaultThemeRoot", defaultThemeRoot);
		
		defaultThemeType = getInitParameter(filterConfig, "defaultThemeType", defaultThemeType);
				
		defaultThemeStyle = getInitParameter(filterConfig, "defaultThemeStyle", defaultThemeStyle);
		
		themeSkin = ThemeSkin.getInstance(filterConfig.getServletContext().getRealPath(""), defaultThemeRoot, defaultThemeType, defaultThemeStyle);
		
		// 获取主题管理服务
		try {
			ServletContext servletContext = filterConfig.getServletContext();
			ApplicationContext ac2 = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
			themeService = (IThemeService)ac2.getBean("ThemeService");
		} catch (Exception e) {
			themeService = null;
		}
		
		if (themeService!=null){
	    	themeService.init(themeSkin, defaultThemeRoot, defaultThemeType, defaultThemeStyle);
			log.debug("主题业务服务已配置！");
		}else{
			log.debug("未配置主题业务服务！");
		}
    }

    private String getInitParameter(FilterConfig filterConfig, String paraName, String defaultValue) {
    	String result = defaultValue;
    	
    	String paraValue = filterConfig.getInitParameter(paraName);
    	if (paraValue!=null){
    		result = paraValue;
    	}
    	
    	return result;
	}

	@Override
    public void doFilter(ServletRequest request, ServletResponse response,
						 FilterChain chain) throws IOException, ServletException {
        // 获得在下面代码中要用的request,response,session对象
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpSession session = servletRequest.getSession();

        if (themeService!=null){
        	// 配置了主题管理服务，使用主题管理服务提供的值
        	Map<String, String> result = themeService.getTheme();
        	String themeType = result.get(ThemeSkin.THEME_TYPE_KEY);
        	session.setAttribute(themeTypeKey,themeType);
        	String themeStyle = result.get(ThemeSkin.THEME_STYLE_KEY);
        	session.setAttribute(themeStyleKey,themeStyle);
        }else{
        	// 未配置主题管理服务，使用默认配置或web环境配置
        	Object value = session.getAttribute(themeRootKey);
        	if (value==null||!(value instanceof ThemeSkin)){
        		session.setAttribute(themeRootKey, themeSkin);
        	}
        	
        	ThemeType themeType;
        	value = session.getAttribute(themeTypeKey);
        	if (value!=null){
        		if (value instanceof ThemeType){
        			themeType = (ThemeType)value;
        		}else if (value instanceof String){
        			themeType = themeSkin.getThemeType((String)value);
        			if (themeType==null){
        				themeType = themeSkin.getDefault();
        			}
        		}else{
    				themeType = themeSkin.getDefault();
        		}
        	}else{
				themeType = themeSkin.getDefault();
        	}
        	
        	if(themeType!=null){
            	session.setAttribute(themeTypeKey, themeType);
            	
                ThemeStyle themeStyle;
            	value = session.getAttribute(themeStyleKey);
            	if (value==null){
                    themeStyle = themeType.getDefault();
            	}else{
            		if (value instanceof ThemeStyle){
                        themeStyle = (ThemeStyle)value;
            		}else if (value instanceof String){
                        themeStyle = themeType.getThemeStyle((String)value);
                        if (themeStyle==null){
                            themeStyle = themeType.getDefault();
                        }
            		}else{
                        themeStyle = themeType.getDefault();
            		}
            	}
            	session.setAttribute(themeStyleKey, themeStyle);
            	
            	log.debug("主题根目录="+session.getAttribute(themeRootKey)+" 主题类型="+session.getAttribute(themeTypeKey)+" 主题风格"+session.getAttribute(themeStyleKey)+" 主样式文件= "+ session.getAttribute(themeMainCssKey));
                
            	String mainCss;
            	value = session.getAttribute(themeMainCssKey);
            	if (value==null){
            		mainCss = themeStyle.getMainCss();
            	}else{
            		if (value instanceof String){
                		mainCss = themeStyle.getMainCss();
            		}else{
                		mainCss = themeStyle.getMainCss();
            		}
            	}
            	session.setAttribute(themeMainCssKey, mainCss);
        	}
		}

    	log.debug("主题根目录="+session.getAttribute(themeRootKey)+" 主题类型="+session.getAttribute(themeTypeKey)+" 主题风格"+session.getAttribute(themeStyleKey)+" 主样式文件= "+ session.getAttribute(themeMainCssKey));
        
    	chain.doFilter(request, response);

//    	CoverResponse coverResponse = new CoverResponse((HttpServletResponse)response);
//        chain.doFilter(request, coverResponse);  
//        //处理替换  
//        String content = coverResponse.getContent();
//        if (content!=null&&content.length()>0){
//        	log.debug("被过滤的有内容");
//        }else{
//        	log.debug("被过滤的没内容！");
//        }
//        content = content.replace("test", "actual");
//        response.getWriter().print(content);  
        
    }
    
	@Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

}